<template>
  <div class="chat-container">
    <div class="header">
      <h2>AI 对话机器人</h2>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>

    <div class="messages-container" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.role, message.error ? 'error' : '']">
        <div class="avatar">
          {{ message.role === 'user' ? '👤' : '🤖' }}
        </div>
        <div class="content">
          <div class="message-text">{{ message.content }}</div>
          <div v-if="message.error" class="error-message">
            {{ message.error }}
          </div>
        </div>
      </div>
      
      <div v-if="loading" class="message ai loading">
        <div class="avatar">🤖</div>
        <div class="content">
          思考中...
          <div class="typing-indicator">
            <span></span><span></span><span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <textarea 
        v-model="userInput" 
        placeholder="输入你的问题..." 
        @keydown.enter.prevent="sendMessage"
        :disabled="loading"
        rows="1"
        ref="textAreaRef"
      ></textarea>
      <button 
        @click="sendMessage" 
        :disabled="loading || !userInput.trim()"
        class="send-button"
      >
        {{ loading ? '发送中...' : '发送' }}
      </button>
    </div>

    <div v-if="showConnectionWarning" class="connection-warning">
      <div class="warning-content">
        <h3>连接问题</h3>
        <p>无法连接到服务器，请检查：</p>
        <ul>
          <li>后端服务是否运行（localhost:8080）</li>
          <li>网络连接是否正常</li>
          <li>浏览器控制台是否有错误信息</li>
        </ul>
        <button @click="showConnectionWarning = false">知道了</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'

export default {
  name: 'ChatWindow',
  setup() {
    // 响应式数据
    const userInput = ref('')
    const messages = ref([])
    const loading = ref(false)
    const messagesContainer = ref(null)
    const textAreaRef = ref(null)
    const isConnected = ref(false)
    const showConnectionWarning = ref(false)

    // API 基础配置
    const API_BASE_URL = 'http://localhost:8080'
    const API_ENDPOINTS = {
      chat: `${API_BASE_URL}/api/chat/simple`,
      health: `${API_BASE_URL}/api/chat/health`
    }

    // 检查后端连接状态
    const checkConnection = async () => {
      try {
        const response = await axios.get(API_ENDPOINTS.health, {
          timeout: 5000 // 5秒超时
        })
        isConnected.value = response.status === 200
        return true
      } catch (error) {
        console.error('后端连接检查失败:', error)
        isConnected.value = false
        return false
      }
    }

    // 发送消息到后端
    const sendMessage = async () => {
      if (!userInput.value.trim() || loading.value) return
      
      // 检查连接状态
      const isBackendConnected = await checkConnection()
      if (!isBackendConnected) {
        showConnectionWarning.value = true
        return
      }

      // 添加用户消息
      const userMessage = userInput.value.trim()
      messages.value.push({ 
        role: 'user', 
        content: userMessage 
      })
      userInput.value = ''
      loading.value = true
      
      // 滚动到底部
      scrollToBottom()
      
      try {
        // 调用后端API - 使用POST请求
        const response = await axios.post(API_ENDPOINTS.chat, {
          message: userMessage
        }, {
          timeout: 30000 // 30秒超时
        })

        // 检查响应状态
        if (response.data.status === 'success') {
          // 添加AI回复到界面
          messages.value.push({ 
            role: 'ai', 
            content: response.data.reply 
          })
        } else {
          // 处理业务逻辑错误
          messages.value.push({ 
            role: 'ai', 
            content: '抱歉，服务暂时不可用。',
            error: response.data.error || '未知错误'
          })
        }
      } catch (error) {
        console.error('API调用失败详情:', error)
        
        let errorMessage = '抱歉，我遇到了问题，请稍后再试。'
        let errorDetail = error.message
        
        if (error.response) {
          // 服务器响应了，但状态码不是2xx
          const status = error.response.status
          if (status === 404) {
            errorMessage = '接口不存在，请检查后端API路径。'
          } else if (status === 500) {
            errorMessage = '服务器内部错误，请检查后端服务。'
          } else if (status === 400) {
            errorMessage = '请求参数错误。'
          }
          errorDetail = error.response.data?.error || errorDetail
        } else if (error.request) {
          // 请求已发出但没有收到响应
          errorMessage = '无法连接到服务器，请确保后端服务正在运行。'
          showConnectionWarning.value = true
        }
        
        messages.value.push({ 
          role: 'ai', 
          content: errorMessage,
          error: errorDetail
        })
      } finally {
        loading.value = false
        // 再次滚动到底部
        scrollToBottom()
        // 焦点回到输入框
        nextTick(() => {
          if (textAreaRef.value) {
            textAreaRef.value.focus()
          }
        })
      }
    }

    // 滚动到消息底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }

    // 初始化示例消息
    onMounted(() => {
      messages.value.push({
        role: 'ai',
        content: '你好！我是基于阿里云百炼的AI助手，有什么可以帮你的吗？'
      })

      // 检查后端连接状态
      checkConnection()
      
      // 焦点到输入框
      nextTick(() => {
        if (textAreaRef.value) {
          textAreaRef.value.focus()
        }
      })
    })

    // 监听连接状态变化
    watch(isConnected, (newValue) => {
      if (newValue && showConnectionWarning.value) {
        showConnectionWarning.value = false
      }
    })

    // 自动调整文本区域高度
    watch(userInput, () => {
      nextTick(() => {
        if (textAreaRef.value) {
          textAreaRef.value.style.height = 'auto'
          textAreaRef.value.style.height = Math.min(textAreaRef.value.scrollHeight, 120) + 'px'
        }
      })
    })

    return {
      userInput,
      messages,
      loading,
      messagesContainer,
      textAreaRef,
      isConnected,
      showConnectionWarning,
      sendMessage
    }
  }
}
</script>

<style lang="scss">
// 导入主样式文件
@import '../styles/main.scss';
</style>